<template>
  <div class="container">
    <!-- 日志记录 -->
    <transition-group name="fade" tag="div">
      <div v-for="(item, index) in weightLogs" :key="index">
        <weight-log
          :day="item.day"
          :month="item.month"
          :year="item.year"
          :bmi="item.bmi"
          :progress="item.changeValue"
          :weight="item.weight"
          :time="item.time"
          :style="{ animationDelay: (index * 0.2) + 's' }"
        ></weight-log>
      </div>
    </transition-group>

    <!-- 弹窗区域：显示体重输入弹窗 -->
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <div class="form-group">
          <label for="weight">请输入体重 (kg):</label>
          <input type="number" v-model="newRecord.weight" placeholder="请输入体重" required />
        </div>
        <button @click="submitForm">提交</button>
        <button @click="cancelForm">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import WeightLog from "@/components/weight-log/weight-log.vue";
import { recordWeightHistory, recordWeight } from '../../api/record.js';  // 引入已封装好的请求方法

export default defineComponent({
  components: {
    WeightLog,
  },
  setup() {
    const showModal = ref(false);  // 控制弹窗显示
    const weightLogs = ref([]);  // 存储体重记录

    const newRecord = reactive({
      weight: '',  // 体重
    });

    // 获取体重记录
    const fetchWeightLogs = async () => {
      try {
        const response = await recordWeightHistory();
        if (response.code === 200) {
          const logs = response.data.map(item => {
            const date = new Date(item.createTime);
            const day = date.getDate();
            const month = date.toLocaleString('default', { month: 'short' });
            const year = date.getFullYear();
            const time = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

            return {
              day: day.toString(),
              month: month,
              year: year.toString(),
              bmi: item.bmi,
              time: time,
              changeValue: item.changeValue || 0, // 默认0
              weight: item.unit === '斤' ? item.weight : item.weight * 2, // 单位转换
            };
          });
          weightLogs.value = logs;
        } else {
          console.error("Failed to fetch data", response.msg);
        }
      } catch (error) {
        console.error("Error fetching data", error);
      }
    };

    // 下拉刷新时弹出体重输入弹窗
    const onPullDownRefresh = () => {
      showModal.value = true;  // 显示弹窗
    };

    // 提交表单
    const submitForm = async () => {
      console.log('submitForm method triggered');  // 调试输出
      if (!newRecord.weight) {
        uni.showToast({
          title: '请输入体重',
          icon: 'none',
        });
        return;
      }

      const weightData = {
        weight: newRecord.weight,
      };

      try {
        const response = await recordWeight(weightData);
        if (response.code === 200) {
          // 提交成功后更新日志
          await fetchWeightLogs();
          // 隐藏弹窗并清空输入框
          showModal.value = false;
          newRecord.weight = '';  // 清空体重输入框
          uni.showToast({
            title: "记录添加成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "记录添加失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("Error submitting weight record", error);
        uni.showToast({
          title: "提交失败，请重试",
          icon: "none",
        });
      }
    };

    // 取消操作，关闭弹窗
    const cancelForm = () => {
      showModal.value = false;
    };

    // 在组件加载时请求数据
    onMounted(() => {
      fetchWeightLogs();
      // 监听下拉刷新事件
      uni.onPullDownRefresh(() => {
        onPullDownRefresh(); // 当用户下拉时调用此方法
      });
    });

    return {
      showModal,
      newRecord,
      weightLogs,
      submitForm,
      cancelForm,
    };
  },
});
</script>

<style scoped>
.container {
  padding: 10px;
  background-color: #f5f5f5;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
}

button {
  background-color: #007BFF;
  color: white;
  padding: 10px 15px;
  border: none;
  cursor: pointer;
  margin-top: 10px;
  width: 100%;
}

button:hover {
  background-color: #0056b3;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease-in-out, transform 0.5s ease-in-out;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
